#pragma once
#include "cancvns.h"
#include "ui_cancvns.h"
#include "myshape.h"
#include "myfreeline.h"
#include "myline.h"
#include "myrect.h"
#include "mycircle.h"
#include "mypentagon.h"
#include "mytriangle.h"
#include "mytext.h"

#include <QMouseEvent>
#include <QPaintEvent>
#include <QWheelEvent>
#include <QPainter>
#include <QPixmap>
#include <QBrush>
#include <QtSvg/QSvgRenderer>
#include <QtSvg/QSvgGenerator>
#include <QColor>
#include <QColorDialog>
#include <QLineEdit>
#include <QByteArray>
#include <QPen>
#include <QXmlStreamReader>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QFile>
#include <QKeyEvent>
#include <QApplication>
#include <QDebug>
#include <QTime>

CanCvns::CanCvns(QWidget *parent) :
    QWidget(parent), 
    ui(new Ui::CanCvns),
    currShape(noshape),
    mWidth(500),
    mHeight(500),
    penSize(3),
    styleIndex(0),
    prePoint(QPoint(10,10)),
    copyPoint(QPoint(10,10)),
    pastePoint(QPoint(10,10)),
    areaSart(QPoint(10,10)),
    areaEnd(QPoint(10,10)),
    shape(NULL),
    seclectedShape(nullptr),
    copyedShape(nullptr),
    dragFlag(false),
    releaseFlag(false),
    saveFlag(false),
    fileType(false),
    fileOpen(false),
    upORdown(false),
    copyFlag(false),
    editFlag(false),
    secondeditFlag(false),
    m_render(nullptr),
    brushColor(Qt::white),
    penColor(Qt::gray),
    fillColor(QColor(0,0,0,0))
{
    ui->setupUi(this);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    fileFlag = QString("My_Svg");
    setInit();

    setFocusPolicy(Qt::StrongFocus); // 设置焦点策略，使窗口部件能够接收键盘事件

    m_render = new QSvgRenderer(this);
    mEdit = new QLineEdit(this);
    // 使用WIN/UNIX/MACOS等操作系统可能有的默认字体
    QFont font;
    font.setPointSize(18);
    #ifdef Q_OS_WIN
    font.setFamilies({"Microsoft YaHei", "SimSun", "KaiTi", "STXingKai"});
    #elif defined(Q_OS_MACOS)
    font.setFamilies({"PingFang SC", "Hiragino Sans GB", "Kai"});
    #else
    font.setFamilies({"Noto Sans CJK SC", "WenQuanYi Micro Hei", "AR PL UKai"});
    #endif
    mEdit->setFont(font);
    mEdit->hide();

    penStyleList << Qt::SolidLine <<Qt::DashLine << Qt::DotLine <<Qt::DashDotLine << Qt::DashDotDotLine;
    setMouseMenu();
}

CanCvns::~CanCvns()
{
    
    clearCvns(); // 首先清理画布对象
    
    delete ui;  // 释放UI资源
    
    if (rightClick) {  // 释放菜单资源
        delete rightClick; // Qt会自动删除所有子Action对象
    }
    
    if (mEdit) { // 安全释放编辑器
        mEdit->disconnect(); // 断开所有信号连接
        delete mEdit;
    }
    
    if (m_render) { // 释放渲染器
        delete m_render;
    }
}

void CanCvns::change(const MyShapeType &tmp)
{
    setInit();
    currShape = tmp;
}

void CanCvns::loadSvgFile(const QString &filename)
{
    setInit();
    //清除缓冲区
    m_render->load(QString(" "));

    fileType = KosoSvgHander(filename);
    if(!fileType) 
    {
        m_render->load(filename);
        fileOpen = true;
    }
}

void CanCvns::saveSvgFile(const QString &filename)
{
    setInit();
    QSvgGenerator generator;
    generator.setFileName(filename);
    generator.setSize(QSize(this->width(),this->height()));
    generator.setViewBox(QRect(0, 0, this->width(), this->height()));
    generator.setTitle(tr("MySVG Drawed"));
    generator.setDescription(fileFlag);
    saveFlag = true;
    QPainter painter(this);
    painter.begin(&generator);
    paintPixmap(painter);
    painter.end();
}

void CanCvns::setPencolor()
{
    breakEdit();
    QColor tmpColor = QColorDialog::getColor(Qt::gray,this,tr("选择画笔颜色"));
    if (false == tmpColor.isValid())
    {
        return;
    }
    penColor = tmpColor;
    if(nullptr != seclectedShape)
    {
        seclectedShape->setPenColor(penColor);
        // 修改画笔颜色后保存状态
        saveToUndoStack();
    }else if(seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            tmpshape->setPenColor(penColor);
        }
        // 修改多个图形画笔颜色后保存状态
        saveToUndoStack();
    }else if(shapeList.size() > 0)
    {
        for(auto tmpshape : shapeList)
        {
            tmpshape->setPenColor(penColor);
        }
        // 修改所有图形画笔颜色后保存状态
        saveToUndoStack();
    }
    update();
}

void CanCvns::setBackcolor()
{
    breakEdit();
    QColor tmpColor = QColorDialog::getColor(Qt::white,this,tr("选择画布颜色"));
    if (false == tmpColor.isValid())
    {
        return;
    }
    brushColor = tmpColor;
    update();
}

void CanCvns::setFillcolor()
{
    breakEdit();
    QColor tmpColor = QColorDialog::getColor(Qt::white,this,tr("选择填充颜色"));
    if (false == tmpColor.isValid())
    {
        return;
    }
    fillColor = tmpColor;
    if(nullptr != seclectedShape)
    {
        seclectedShape->setFillColor(fillColor);
        // 修改填充颜色后保存状态
        saveToUndoStack();
    }else if(seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            tmpshape->setFillColor(fillColor);
        }
        // 修改多个图形填充颜色后保存状态
        saveToUndoStack();
    }else if(shapeList.size() > 0)
    {
        for(auto tmpshape : shapeList)
        {
            tmpshape->setFillColor(fillColor);
        }
        // 修改所有图形填充颜色后保存状态
        saveToUndoStack();
    }
}

void CanCvns::setDragable()
{
    setInit();
    dragFlag = true;
}


void CanCvns::wheelEvent(QWheelEvent *event)
{
    breakEdit();
    //diff值表示每次滚轮滚动一定的值，图片大小改变的比例
    const double diff = 0.1;
    //利用QWheelEvent的delta()函数获得滚轮滚动的距离值，通过此值来判断滚轮滚动的方向
    qreal factor = event->angleDelta().y() > 0 ? 1 + diff : 1 - diff;

    //缩放图形
    if(nullptr != seclectedShape)
    {
        seclectedShape->zoomShape(factor);
        update();
    }else if(seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            tmpshape->zoomShape(factor);
        }
        update();
    }else
    {
        factor = int( this->width() * factor) < 50   ? factor + diff : factor;
        factor = int( this->height() * factor) > 900 ? factor - diff : factor;
        factor = int( this->height() * factor) < 25  ? factor + diff : factor;
        factor = int( this->width() * factor) > 1800 ? factor - diff : factor;
        //缩放画布
        mWidth = int( this->width() * factor);
        mHeight = int( this->height() * factor);
        zoomChange(factor);

        //调整尺寸
        emit tobarSizeInfo(mWidth,mHeight);
        event->accept();
    }
}

void CanCvns::newCvns()
{
    setInit();
    if(shapeList.size() > 0 || fileOpen)
    {
        QMessageBox msg(this);
        msg.setWindowTitle(tr("新建画布"));
        msg.setWindowIcon(QIcon(":/image/newcancvs_s.png"));
        msg.setText(tr("clear the cancvns yes or no"));
        msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        if(msg.exec() == QMessageBox::Ok)
        {
            clearCvns();
            brushColor = Qt::white;
            resetSize(500,500);
            emit tobarSizeInfo(500,500);
        }else{

        }
    }else
    {
        brushColor = Qt::white;
        resetSize(500,500);
        emit tobarSizeInfo(500,500);
    }
    update();
}

void CanCvns::clearCvns()
{
    setInit();
    
    // 清空图形列表，释放内存
    if(!shapeList.isEmpty())
    {
        clearShapeList(shapeList);
        
        // 重置所有指针和状态
        shape = nullptr;
        seclectedShape = nullptr;
        copyedShape = nullptr;
        
        // 清空其他列表
        copyShapeList.clear();
        seclectedShapeList.clear();
    }

    // 清理渲染器
    if(nullptr != shape)
    {
        delete shape;
        shape = nullptr;
    }

    // 重置文件相关状态
    if(false == fileType)
    {
        m_render->load(QString(" "));
        fileOpen = false;
    }
    
    // 清空撤销栈，释放内存
    while(!undoStack.isEmpty()) {
        QList<MyShape*> state = undoStack.pop();
        clearShapeList(state);
    }
    
    update();
}

void CanCvns::resetSize(const int &width, const int &height)
{
    //缩放画布
    qreal wfactor = width / this->width();
    qreal hfactor = height / this->height();
    mWidth = width;
    mHeight = height;
    pixMap.scaled(wfactor, hfactor,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);

    //调整尺寸
    this->resize(mWidth,mHeight);
    pixMap.scaled(mWidth,mHeight);
    update();
}


void CanCvns::onCopyshapeTriggered()
{
    // 复制单个图形
    if(nullptr != seclectedShape)
    {
        copyedShape = seclectedShape;
        copyShapeList.clear(); // 确保清空多选列表
        copyFlag = true;
        return; // 提前返回，避免不必要的检查
    }
    
    // 复制多个图形
    if (seclectedShapeList.size() > 0)
    {
        copyShapeList.clear();
        // 预分配足够空间
        copyShapeList.reserve(seclectedShapeList.size());
        
        for(auto tmpshape : seclectedShapeList)
        {
            if(tmpshape && tmpshape->isAreaSeclect(areaSart, areaEnd))
            {
                copyShapeList << tmpshape;
            }
        }
        copyedShape = nullptr; // 确保单图形复制指针为空
        copyFlag = true;
    }
}

void CanCvns::onPasteshapeTriggered()
{
    bool needUpdate = false;
    
    // 粘贴单个图形
    if(nullptr != copyedShape)
    {
        pasteCopedShape(copyedShape);
        needUpdate = true;
    }
    // 粘贴多个图形
    else if (!copyShapeList.isEmpty())
    {
        for(auto tmpshape : copyShapeList)
        {
            if (tmpshape) {
                pasteCopedShape(tmpshape);
                needUpdate = true;
            }
        }
    }
    
    // 优化：仅在实际发生粘贴操作时才更新画布和保存撤销状态
    if (needUpdate) {
        // 粘贴完成后取消选中状态
        seclectedShape = nullptr;
        seclectedShapeList.clear();
        
        // 保存到撤销栈
        saveToUndoStack();
        update();
    }
}

void CanCvns::onDeleteshapeTriggered()
{
    if(nullptr != seclectedShape)
    {
        if(seclectedShape == shape)
        {
            shape = nullptr;
        }
        if(seclectedShape == copyedShape)
        {
            copyedShape = nullptr;
        }

        if(copyShapeList.contains(seclectedShape))
        {
            copyShapeList.removeOne(seclectedShape);
        }
        if(seclectedShapeList.contains(seclectedShape))
        {
            seclectedShapeList.removeOne(seclectedShape);
        }

        shapeList.removeOne(seclectedShape);
        delete seclectedShape;
        seclectedShape = nullptr;
    }else if (seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            if(tmpshape == shape)
            {
                shape = nullptr;
            }
            if(tmpshape == copyedShape)
            {
                copyedShape = nullptr;
            }
            seclectedShapeList.removeOne(tmpshape);
            if(shapeList.contains(tmpshape))
            {
                shapeList.removeOne(tmpshape);
            }
            if(copyShapeList.contains(tmpshape))
            {
                copyShapeList.removeOne(tmpshape);
            }
            delete tmpshape;
            tmpshape = nullptr;
        }

    }
    update();
}
void CanCvns::resetpenSize(const int &pensize)
{
    breakEdit();
    penSize = pensize;
    if(nullptr != seclectedShape)
    {
        seclectedShape->setPenSize(penSize);
        // 修改画笔大小后保存状态
        saveToUndoStack();
    }else if(seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            tmpshape->setPenSize(penSize);
        }
        // 修改多个图形画笔大小后保存状态
        saveToUndoStack();
    }else if(shapeList.size() > 0)
    {
        for(auto tmpshape : shapeList)
        {
            tmpshape->setPenSize(penSize);
        }
        // 修改所有图形画笔大小后保存状态
        saveToUndoStack();
    }
    update();
}

void CanCvns::resetpenStyle(const int &StyleIndex)
{
    breakEdit();
    styleIndex = StyleIndex;
    if(nullptr != seclectedShape)
    {
        seclectedShape->setPenStyle(penStyleList[styleIndex]);
        // 修改画笔样式后保存状态
        saveToUndoStack();
    }else if(seclectedShapeList.size() > 0)
    {
        for(auto tmpshape : seclectedShapeList)
        {
            tmpshape->setPenStyle(penStyleList[styleIndex]);
        }
        // 修改多个图形画笔样式后保存状态
        saveToUndoStack();
    }else if(shapeList.size() > 0)
    {
        for(auto tmpshape : shapeList)
        {
            tmpshape->setPenStyle(penStyleList[styleIndex]);
        }
        // 修改所有图形画笔样式后保存状态
        saveToUndoStack();
    }
    update();
}

void CanCvns::onSecondeditTriggered()
{
    if(nullptr == seclectedShape || MyShapeType::text != seclectedShape->getType())
        return;
    //二次绘制文字
    mEdit->setFocus();
    mEdit->setGeometry(seclectedShape->getStart().x(),seclectedShape->getStart().y(),90,40);
    mEdit->setText(static_cast<MyText*>(seclectedShape)->getDrawText());
    static_cast<MyText*>(seclectedShape)->setDrawText("");
    secondeditFlag = true;
    update();
    mEdit->show();
    connect(mEdit, &QLineEdit::textEdited, this, [&]{
        mEdit->setFixedSize(mEdit->fontMetrics().horizontalAdvance(mEdit->text()) + 10, mEdit->fontMetrics().height() * 2);});
    connect(mEdit, &QLineEdit::editingFinished, this, [&]{});
}


void CanCvns::paintEvent(QPaintEvent *event)
{
    QPainter painter(&pixMap);
    saveFlag = false;
    paintPixmap(painter);
}

void CanCvns::mousePressEvent(QMouseEvent *event)
{
    // 当鼠标点击时，获取焦点
    setFocus();
    
    prePoint = event->pos();
    breakEdit();

    if(currShape != MyShapeType::noshape && Qt::LeftButton == event->button())
    {
        switch (currShape)
        {
        case MyShapeType::freeline:
        {
            shape = new MyFreeLine();
            break;
        }
        case MyShapeType::line:
        {
            shape = new MyLine();
            break;
        }
        case MyShapeType::rect:
        {
            shape = new MyRect();
            break;
        }
        case MyShapeType::circle:
        {
            shape = new MyCircle();
            break;
        }
        case MyShapeType::pentagon:
        {
            shape = new MyPentagon();
            break;
        }
        case MyShapeType::trangle:
        {
            shape = new MyTriangle();
            break;
        }
        case MyShapeType::text:
        {
            if(false == editFlag)
            {
                shape = new MyText();
                mEdit->setGeometry(event->x(),event->y(),90,40);
                mEdit->setPlaceholderText("input");
                mEdit->setFocus();
                mEdit->show();
                connect(mEdit, &QLineEdit::textEdited, this, [&]{
                    mEdit->setFixedSize(mEdit->fontMetrics().horizontalAdvance(mEdit->text()) + 10, mEdit->fontMetrics().height() * 2);
                });
                connect(mEdit, &QLineEdit::editingFinished, this, [&]{});
                editFlag = true;
            }
            break;
        }
        default:
        {
            shape = nullptr;
            break;
        }
        }

        if(nullptr != shape)
        {
            //绘制自由线
            if(MyShapeType::freeline == shape->getType())
            {
                static_cast<MyFreeLine*>(shape)->addPoint(event->pos());
            }
            shape->setPenSize(penSize);
            shape->setPenStyle(penStyleList[styleIndex]);
            shape->setPenColor(penColor);
            shape->setStart(event->pos());
        }
    }else if(event->button() == Qt::LeftButton && dragFlag)
    {
        seclectedShape = nullptr;
        //确定选中的对象
        foreach(MyShape * preshape, shapeList)
        {
            if(preshape->isSeclect(prePoint))
            {
                seclectedShape = preshape;
            }else
            {
            }
        }

        if(nullptr != seclectedShape)
        {
            seclectedShapeList.clear();
        }else
        {
            areaSart = event->pos();
        }
    }else if (event->button() == Qt::RightButton)
    {
        onLeftClickOut();
        if(copyFlag)
        {
            pastePoint = event->pos();
        }else
        {
            copyPoint = event->pos();
        }
        resetMouseMenu();
        rightClick->popup(event->globalPos());
    }else
    {
        setDragable();
    }
    releaseFlag = false;
}

void CanCvns::mouseMoveEvent(QMouseEvent *event)
{
    if(dragFlag)
    {
        if(nullptr != seclectedShape)
        {
            seclectedShape->dragMove(prePoint,event->pos());
        }else if(seclectedShapeList.size() > 0)
        {
            for (auto tmpshape : seclectedShapeList)
            {
                tmpshape->dragMove(prePoint,event->pos());
            }
        }else if(nullptr == seclectedShape)
        {
            areaEnd = event->pos();
        }
        prePoint = event->pos();
        update();
    }else if(nullptr != shape && false == releaseFlag)
    {
        if(MyShapeType::text != currShape && MyShapeType::freeline != currShape)
        {
            shape->setEnd(event->pos());
        }

        if(MyShapeType::freeline == currShape)
        {
            static_cast<MyFreeLine*>(shape)->addPoint(event->pos());
            static_cast<MyFreeLine*>(shape)->getArea();
        }else
        {
        }
        update();
    }
}


void CanCvns::mouseReleaseEvent(QMouseEvent *event)
{
    if(dragFlag)
    {
        if(nullptr != seclectedShape)
        {
            seclectedShape->dragMove(prePoint,event->pos());
            prePoint = event->pos();
            update();
            // 在拖动单个图形后保存状态
            saveToUndoStack();
        }else if(seclectedShapeList.size()>0)
        {
            for (auto tmpshape : seclectedShapeList)
            {
                tmpshape->dragMove(prePoint,event->pos());
            }
            prePoint = event->pos();
            update();
            // 在拖动多个图形后保存状态
            saveToUndoStack();
        }else if(nullptr == seclectedShape)
        {
            areaEnd = event->pos();
            for(auto tmpshape : shapeList)
            {
                if(tmpshape->isAreaSeclect(areaSart,areaEnd))
                {
                    seclectedShapeList << tmpshape;
                }
            }
            if(seclectedShapeList.size() > 0)
            {
                update();
            }
        }
    }else if(nullptr != shape)
    {
        if(MyShapeType::text != currShape && MyShapeType::freeline != currShape)
        {
            shape->setEnd(event->pos());
        }
        if( MyShapeType::freeline == currShape)
        {
            static_cast<MyFreeLine*>(shape)->addPoint(event->pos());
            static_cast<MyFreeLine*>(shape)->getArea();
            update();
        }else
        {
            update();
        }

        if(true == editFlag)
        {
        }else
        {
            onLeftClickOut();
        }
    }
    releaseFlag = true;
    update();
}

void CanCvns::onLeftClickOut()
{
    if(nullptr != shape)
    {
        if(MyShapeType::text == shape->getType())
        {
        } else if(MyShapeType::noshape == shape->getType() || shape->getStart() == shape->getEnd()
                  || 0 == (shape->getStart().x() * shape->getEnd().x()))
        {
            delete shape;
            shape = nullptr;
        }else
        {
            shapeList<<shape;
            shape = nullptr;
            // 在添加新图形后保存状态到撤销栈
            saveToUndoStack();
        }
    }
}


void CanCvns::setMouseMenu()
{
    rightClick = new QMenu(this);
    copyShape = new QAction(rightClick);
    pasteShape = new QAction(rightClick);
    deleteShape = new QAction(rightClick);
    toUp = new QAction(rightClick);
    toDown = new QAction(rightClick);
    secondEdit = new QAction(rightClick);
    copyShape->setText(tr("复制(ctrl+c)"));
    pasteShape->setText(tr("粘贴(ctrl+v)"));
    deleteShape->setText(tr("删除(delete)"));
    toUp->setText(tr("置于顶层"));
    toDown->setText(tr("置于底层"));
    secondEdit->setText(tr("编辑文本"));
    copyShape->setIcon(QIcon(":/image/copyshape.png"));
    pasteShape->setIcon(QIcon(":/image/pasteshape.png"));
    deleteShape->setIcon(QIcon(":/image/deleteshape.png"));
    toUp->setIcon(QIcon(":/image/toup.png"));
    toDown->setIcon(QIcon(":/image/todown.png"));
    secondEdit->setIcon(QIcon(":/image/secondedit.png"));
    rightClick->addAction(copyShape);
    rightClick->addAction(pasteShape);
    rightClick->addAction(deleteShape);
    rightClick->addAction(toUp);
    rightClick->addAction(toDown);
    rightClick->addAction(secondEdit);
    connect(deleteShape,SIGNAL(triggered()),this,SLOT(onDeleteshapeTriggered()));
    connect(copyShape,SIGNAL(triggered()),this,SLOT(onCopyshapeTriggered()));
    connect(pasteShape,SIGNAL(triggered()),this,SLOT(onPasteshapeTriggered()));
    connect(toUp,&QAction::triggered,this,[&]{ upORdown = true; swapShape();});
    connect(toDown,&QAction::triggered,this,[&]{ upORdown = false; swapShape();});
    connect(secondEdit,SIGNAL(triggered()),this,SLOT(onSecondeditTriggered()));
}

void CanCvns::resetMouseMenu()
{
    copyShape->setEnabled(false);
    //当未选中单个对象
    if(nullptr == seclectedShape)
    {
        //存在复制的对象指针
        if(nullptr != copyedShape || copyShapeList.size() > 0)
        {
            pasteShape->setEnabled(true);
        }else
        {
            pasteShape->setEnabled(false);
        }
        // 选中多个对象
        if(seclectedShapeList.size() > 0)
        {
            copyShape->setEnabled(true);
            deleteShape->setEnabled(true);
        }else
        {
            copyShape->setEnabled(false);
            deleteShape->setEnabled(false);
        }
        toUp->setEnabled(false);
        toDown->setEnabled(false);
        secondEdit->setEnabled(false);
        update();
    }else     //当选中单个对象
    {
        //当未选中单个text对象
        if(MyShapeType::text == seclectedShape->getType())
        {
            secondEdit->setEnabled(true);
        }else
        {
            secondEdit->setEnabled(false);
        }
        copyShape->setEnabled(true);
        pasteShape->setEnabled(false);
        deleteShape->setEnabled(true);
        toUp->setEnabled(true);
        toDown->setEnabled(true);
    }
}

void CanCvns::paintPixmap(QPainter &painter)
{
    painter.setRenderHints(QPainter::Antialiasing,true);
    painter.begin(this);
    //画布背景色brushColor
    painter.setBrush(brushColor);
    painter.drawRect(0, 0, this->width(), this->height());

    //画文件
    if(nullptr != m_render && false == fileType)
    {
        pixMap.fill(Qt::transparent);
        pixMap.scaled(this->size(),Qt::KeepAspectRatio);
        m_render->render(&painter);
    }

    //设置透明
    painter.setBrush(QColor(0,0,0,0));

    //画界面
    if(shapeList.size()>0)
    {
        foreach(MyShape * tmpshape, shapeList)
        {
            tmpshape->paint(painter);
        }
    }

    //绘制新图形
    if(nullptr != shape && false == saveFlag)
    {
        if(MyShapeType::noshape == shape->getType() || shape->getStart() == shape->getEnd()
                || 0 == (shape->getStart().x() * shape->getEnd().x()))
        {

        }else
        {
            shape->paint(painter);
            // drawdotBox调用
            // if( currShape != MyShapeType::noshape && !dragFlag)
            // {
            //     shape->drawdotBox(painter);
            // }
        }
    }

    //拖动图形
    if(true == dragFlag && false == saveFlag && false == editFlag)
    {

        if(nullptr != seclectedShape)
        {
            //drawtoBox
            seclectedShape->drawdotBox(painter);
        }else
        {
            if(seclectedShapeList.size()>0)
            {
                for (auto tmpshape : seclectedShapeList)
                {
                    tmpshape->drawdotBox(painter);
                }
            }
        }

    }
    if(false == saveFlag && nullptr == shape && 0 == seclectedShapeList.size() && nullptr == seclectedShape)
    {
        drawSelectArea(painter);
    }

    painter.end();
}

void CanCvns::zoomChange(const qreal &factor)
{
    const qreal currentZoom = factor;
    if ((factor < 1 && currentZoom < 0.1) || (factor > 1 && currentZoom > 10))
        return;
    foreach(MyShape * tmpshape, shapeList)
    {
        tmpshape->zoomChange(factor);
    }
    if(nullptr != shape)
    {
        shape->zoomChange(factor);
    }
}

void CanCvns::setInit()
{
    breakEdit();
    dragFlag = false;
    seclectedShapeList.clear();
    copyFlag = false;
    saveFlag = false;
    fillColor = QColor(0,0,0,0);
    fileType = false;
    copyFlag = false;
    //表示当前功能为非图形绘制
    currShape = MyShapeType::noshape;
}

bool CanCvns::KosoSvgHander(const QString &filename)
{
    QXmlStreamReader reader;
    QList<MyShape*> tmpList;
    //记录属性
    QString dasharray;
    int tmpStyle = 0;
    int stroke_width = 3;
    int font_size = 28;

    QFile file(filename);
    if (false == file.open(QFile::ReadOnly | QFile::Text)) {
        qDebug() << "无法打开文件:" << filename;
        return false;
    }

    //存储点坐标
    QString points;
    QStringList pointlist;
    
    QString fillColor;
    QString mfillColor;

    QString strokeColor;
    bool fileType = false;
    bool polylineFlag = false;
    bool textFlag = false;
    bool sizeFlag = true;
    bool rectFlag = false;
    bool circleFlag = false;
    bool pathFlag = false;
    
    QString descText;//区别是否为自己生成的文件

    QString textText;
    MyShapeType shapetype = MyShapeType::noshape;

    int x = 0, y = 0, width = 0, height = 0, sx = 0, sy = 0, mwidth = 500, mheight = 500;

    
    reader.setDevice(&file); //将文件设置成xml阅读器的输入设备

    //读SVG文件
    while (!reader.atEnd())
    {
        if (reader.readNext() == QXmlStreamReader::Invalid) {
            qDebug() << "XML解析错误:" << reader.errorString();
            file.close();
            // 清理已创建的对象，防止内存泄漏
            qDeleteAll(tmpList);
            return false;
        }
        
        // 只处理开始元素
        if (reader.tokenType() != QXmlStreamReader::StartElement) {
            continue;
        }
            
        shapetype = MyShapeType::noshape;
        shape = nullptr; // 重置shape指针，避免使用未初始化的指针
        
        //标签<g>
        if (reader.name() == "g") 
        {
            if (!points.isEmpty())
            {
                // 处理路径数据
                points.replace("M", " ").replace("L", " ").replace(",", " ");
                // 移除多余空格
                while (points.contains("  ")) points.replace("  ", " ");
                points = points.trimmed();
                pointlist = points.split(' ', Qt::SkipEmptyParts);
                
                //待完善,前不支持曲线
                if (points.contains('c') || points.contains('z') || points.contains('C') || points.contains('Z'))
                {
                    fileType = false;
                    file.close();
                    qDeleteAll(tmpList);
                    return fileType;
                }
            }

            //解析矢量图形
            if (pathFlag)
            {
                // 使用安全索引检查
                if (pointlist.size() == 8)
                {
                    shape = new MyTriangle();
                    shapetype = MyShapeType::trangle;
                    if (shape) {
                        shape->setPos(pointlist.value(0).toInt(), pointlist.value(5).toInt(), 
                                      pointlist.value(2).toInt(), pointlist.value(3).toInt());
                        shape->setFillColor(transQColor(fillColor));
                    }
                }
                else if (pointlist.size() == 14)
                {
                    shape = new MyPentagon();
                    shapetype = MyShapeType::pentagon;
                    if (shape) {
                        shape->setPos(pointlist.value(10).toInt(), pointlist.value(1).toInt(), 
                                      pointlist.value(4).toInt(), pointlist.value(7).toInt());
                        shape->setFillColor(transQColor(fillColor));
                    }
                }
                else if (pointlist.size() > 14)
                {
                    shape = new MyFreeLine();
                    shapetype = MyShapeType::freeline;
                    if (shape) {
                        for (int i = 0; i < pointlist.size() - 1; i += 2) {
                            static_cast<MyFreeLine*>(shape)->addPoint(
                                QPoint(pointlist.value(i).toInt(), pointlist.value(i+1).toInt()));
                        }
                        static_cast<MyFreeLine*>(shape)->getArea();
                    }
                }
                points.clear();
            }
            else if (polylineFlag)
            {
                points.replace(',', ' ');
                // 移除多余空格
                while (points.contains("  ")) points.replace("  ", " ");
                points = points.trimmed();
                pointlist = points.split(' ', Qt::SkipEmptyParts);

                if (pointlist.size() >= 4) // 至少需要两个点(4个坐标)
                {
                    shape = new MyLine();
                    shapetype = MyShapeType::line;
                    if (shape) {
                        shape->setPos(pointlist.value(0).toInt(), pointlist.value(1).toInt(), 
                                      pointlist.value(2).toInt(), pointlist.value(3).toInt());
                    }
                }
                else
                {
                    fileType = false;
                }
                points.clear();
            }
            else if (rectFlag && !sizeFlag)
            {
                shape = new MyRect();
                shapetype = MyShapeType::rect;
                if (shape) {
                    shape->setPos(x, y, x + width, y + height);
                    shape->setFillColor(transQColor(fillColor));
                }
            }
            else if (circleFlag)
            {
                shape = new MyCircle();
                shapetype = MyShapeType::circle;
                if (shape) {
                    shape->setPos(x - width, y - height, x + width, y + height);
                    shape->setFillColor(transQColor(fillColor));
                }
            }
            else if (textFlag)
            {
                shape = new MyText();
                shapetype = MyShapeType::text;
                if (shape) {
                    static_cast<MyText*>(shape)->setSPos(sx, sy);
                    static_cast<MyText*>(shape)->setDrawText(textText);
                }
            }

            // 添加解析图形到临时列表，管理周期
            if (shapetype != MyShapeType::noshape && shape != nullptr)
            {
                shape->setPenColor(transQColor(strokeColor));
                shape->setPenStyle(penStyleList.value(tmpStyle % penStyleList.size())); // 避免索引越界
                shape->setPenSize(stroke_width > 0 ? stroke_width : 1); // 避免无效画笔宽度
                
                if (shapetype == MyShapeType::text)
                {
                    static_cast<MyText*>(shape)->setFontSize(font_size > 0 ? font_size : 12);
                }
                tmpList << shape;
                shape = nullptr; // 已添加到列表，重置指针
            }
            else if (shape != nullptr) {
                // 如果形状创建但未添加到列表，删除它
                delete shape;
                shape = nullptr;
            }

            // 从g标签读取属性
            if (reader.attributes().hasAttribute("fill"))
                fillColor = reader.attributes().value("fill").toString();
            if (reader.attributes().hasAttribute("stroke"))
                strokeColor = reader.attributes().value("stroke").toString();
            if (reader.attributes().hasAttribute("stroke-dasharray")) {
                dasharray = reader.attributes().value("stroke-dasharray").toString();
                tmpStyle = penstyleGetter(dasharray);
            }
            if (reader.attributes().hasAttribute("stroke-width")) {
                bool ok;
                int width = reader.attributes().value("stroke-width").toInt(&ok);
                if (ok) stroke_width = width;
            }
            if (reader.attributes().hasAttribute("font-size")) {
                bool ok;
                int size = reader.attributes().value("font-size").toInt(&ok);
                if (ok) font_size = size;
            }

            // 重置标志
            polylineFlag = rectFlag = circleFlag = textFlag = pathFlag = false;
        }
        else if (reader.name() == "text")
        {
            textFlag = true;
            // 安全读取属性
            sx = reader.attributes().hasAttribute("x") ? reader.attributes().value("x").toInt() : 0;
            sy = reader.attributes().hasAttribute("y") ? reader.attributes().value("y").toInt() : 0;
            textText = reader.readElementText();
        }
        else if (reader.name() == "desc")
        {
            descText = reader.readElementText();
            if (descText == fileFlag)
            {
                fileType = true;
            }
            else {
                file.close();
                qDeleteAll(tmpList);
                return false;
            }
        }
        else if (reader.name() == "polyline")
        {
            polylineFlag = true;
            points = reader.attributes().value("points").toString();
        }
        else if (reader.name() == "path")
        {
            pathFlag = true;
            points = reader.attributes().value("d").toString();
        }
        else if (reader.name() == "rect")
        {
            // 安全读取属性
            bool hasX = reader.attributes().hasAttribute("x");
            bool hasWidth = reader.attributes().hasAttribute("width");
            int rect_x = hasX ? reader.attributes().value("x").toInt() : 0;
            
            if (rect_x == 0)
            {
                if (sizeFlag && hasWidth)
                {
                    mwidth = reader.attributes().value("width").toInt();
                    mheight = reader.attributes().hasAttribute("height") ? 
                              reader.attributes().value("height").toInt() : mwidth;
                    mfillColor = fillColor;
                }
                sizeFlag = false;
            }
            else if (hasWidth && reader.attributes().value("width").toInt() != 0)
            {
                rectFlag = true;
                x = rect_x;
                y = reader.attributes().hasAttribute("y") ? reader.attributes().value("y").toInt() : 0;
                width = reader.attributes().value("width").toInt();
                height = reader.attributes().hasAttribute("height") ? 
                         reader.attributes().value("height").toInt() : width;
            }
        }
        else if (reader.name() == "ellipse")
        {
            bool hasRx = reader.attributes().hasAttribute("rx");
            if (hasRx && reader.attributes().value("rx").toInt() != 0)
            {
                circleFlag = true;
                x = reader.attributes().hasAttribute("cx") ? reader.attributes().value("cx").toInt() : 0;
                y = reader.attributes().hasAttribute("cy") ? reader.attributes().value("cy").toInt() : 0;
                width = reader.attributes().value("rx").toInt();
                height = reader.attributes().hasAttribute("ry") ? 
                         reader.attributes().value("ry").toInt() : width;
            }
        }
        // 支持circle元素
        else if (reader.name() == "circle")
        {
            bool hasR = reader.attributes().hasAttribute("r");
            if (hasR && reader.attributes().value("r").toInt() != 0)
            {
                circleFlag = true;
                x = reader.attributes().hasAttribute("cx") ? reader.attributes().value("cx").toInt() : 0;
                y = reader.attributes().hasAttribute("cy") ? reader.attributes().value("cy").toInt() : 0;
                width = height = reader.attributes().value("r").toInt();
            }
        }
    }

    // 检查是否有解析错误
    if (reader.hasError()) {
        qDebug() << "XML解析错误:" << reader.errorString();
        file.close();
        qDeleteAll(tmpList);
        return false;
    }
    
    file.close();

    if (fileType)
    {
        resetSize(mwidth, mheight);
        brushColor = transQColor(mfillColor);
        
        // 将临时列表中的形状转移到shapeList中
        if (!tmpList.isEmpty()) {
            shapeList.append(tmpList);
            tmpList.clear(); // 清空临时列表但不删除对象
        }
        update();
    }
    else {
        qDeleteAll(tmpList);// 如果不是我们的文件格式（My_Svg），清理临时创建的形状
    }
    
    return fileType;
}

QColor CanCvns::transQColor(const QString &ColorStr)
{
    if(!ColorStr.startsWith("#"))
    {
        if(ColorStr == "black")
        {
            return Qt::black;
        }else if(ColorStr == "none")
        {
            return Qt::gray;
        }else
        {
            return Qt::white;
        }
    }else if(ColorStr == "#000000" )
    {
        return QColor(0,0,0,0);
    }else
    {
        QString tmps="0x"+ColorStr.right(6);
        return QColor(tmps.toUInt(NULL,16));
    }
}

void CanCvns::swapShape()
{
    MyShape *tmpshape = seclectedShape;
    if( shapeList.size() > 1)
    {
        if(true == upORdown)
        {
            shapeList.removeOne(tmpshape);
            tmpshape = nullptr;
            shapeList.push_back(seclectedShape);
            // 置顶后保存状态
            saveToUndoStack();
            update();
        }else
        {
            shapeList.removeOne(tmpshape);
            tmpshape = nullptr;
            shapeList.push_front(seclectedShape);
            // 置底后保存状态
            saveToUndoStack();
            update();
        }
    }
}

int CanCvns::penstyleGetter(const QString &Dasharray)
{
    QStringList tmpstyle = Dasharray.split(",");
    if(tmpstyle.size() == 4)
    {
        return 3;
    }else if(tmpstyle.size() == 6)
    {
        return 4;
    }else if(tmpstyle.size() == 2)
    {
        int ax = tmpstyle.at(0).toInt();
        int bx = tmpstyle.at(1).toInt();
        if(ax < bx)
        {
            return 2;
        }else
        {
            return 1;
        }
    }
    return 0;
}

void CanCvns::pasteCopedShape(MyShape *copedShape)
{
    if(nullptr == copedShape)
        return;
    
    // 创建新图形对象
    MyShape* newShape = nullptr;
    
    // 使用多态创建正确类型的图形对象
    switch(copedShape->getType())
    {
    case MyShapeType::freeline:
        newShape = new MyFreeLine(*static_cast<MyFreeLine*>(copedShape));
        break;
    case MyShapeType::line:
        newShape = new MyLine(*static_cast<MyLine*>(copedShape));
        break;
    case MyShapeType::rect:
        newShape = new MyRect(*static_cast<MyRect*>(copedShape));
        break;
    case MyShapeType::circle:
        newShape = new MyCircle(*static_cast<MyCircle*>(copedShape));
        break;
    case MyShapeType::pentagon:
        newShape = new MyPentagon(*static_cast<MyPentagon*>(copedShape));
        break;
    case MyShapeType::trangle:
        newShape = new MyTriangle(*static_cast<MyTriangle*>(copedShape));
        break;
    case MyShapeType::text:
        newShape = new MyText(*static_cast<MyText*>(copedShape));
        break;
    default:
        return; // 直接返回，避免后续处理
    }
    
    if(newShape)
    {
        QPoint sourcePoint = copyPoint;
        QPoint targetPoint = pastePoint;
        
        if (sourcePoint == targetPoint || (sourcePoint.x() == 10 && sourcePoint.y() == 10)) {
            // 默认右下偏移20像素
            targetPoint = QPoint(copedShape->getStart().x() + 20, copedShape->getStart().y() + 20);
        }
        
        newShape->dragMove(sourcePoint, targetPoint);
        
        // 添加到图形列表
        shapeList.append(newShape);
    }
    
    // 粘贴完成后取消选中状态
    seclectedShape = nullptr;
    seclectedShapeList.clear();
    
    // 更新画布
    update();
}

void CanCvns::drawSelectArea(QPainter &painter)
{
    QRect boundingRect;
    QPen pen = painter.pen();
    pen.setColor(Qt::cyan);
    pen.setWidth(penSize);
    pen.setStyle(penStyleList[styleIndex]);
    painter.setPen(pen);
    pen.setBrush(Qt::NoBrush);
    painter.setBrush(Qt::NoBrush);
    if(false == releaseFlag)
    {
        painter.drawRect(boundingRect.adjusted(areaSart.x(), areaSart.y(), areaEnd.x(),  areaEnd.y()));
    }
}

void CanCvns::breakEdit()
{
    if(true == secondeditFlag)
    {
        static_cast<MyText*>(seclectedShape)->setDrawText(mEdit->text());
        mEdit->hide(); mEdit->clear();
        disconnect(mEdit,&QLineEdit::editingFinished,0,0);
        secondeditFlag = false;
        // 二次编辑文本后保存状态
        saveToUndoStack();
        update();
    }
    if(shape != nullptr && true == editFlag)
    {
        static_cast<MyText*>(shape)->setDrawText(mEdit->text());
        disconnect(mEdit,&QLineEdit::editingFinished,0,0);
        mEdit->hide(); mEdit->clear(); editFlag = false;
        if(MyShapeType::text == shape->getType())
        {
            shapeList<<shape;
            shape = nullptr;
            // 添加文本后保存状态
            saveToUndoStack();
        }
        update();
    }
}

void CanCvns::keyPressEvent(QKeyEvent *event)
{
    // 在处理事件之前，打印一条日志来确认事件被触发
    qDebug() << "键盘事件被触发: " << event->key();
    
    // Ctrl+C 复制
    if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) {
        if (seclectedShape != nullptr) {
            copyedShape = seclectedShape;
            copyFlag = true;
            qDebug() << "复制图形";
        } else if (seclectedShapeList.size() > 0) {
            copyShapeList.clear();
            for (auto tmpshape : seclectedShapeList) {
                copyShapeList << tmpshape;
            }
            copyFlag = true;
            qDebug() << "复制多个图形";
        }
    }
    // Ctrl+V 粘贴
    else if (event->key() == Qt::Key_V && event->modifiers() == Qt::ControlModifier) {
        if (copyFlag && copyedShape != nullptr) {
            pasteCopedShape(copyedShape);
            saveToUndoStack();
            qDebug() << "粘贴图形";
        } else if (copyFlag && copyShapeList.size() > 0) {
            for (auto tmpshape : copyShapeList) {
                pasteCopedShape(tmpshape);
            }
            saveToUndoStack();
            qDebug() << "粘贴多个图形";
        }
        
        // 粘贴完成后取消选中状态
        seclectedShape = nullptr;
        seclectedShapeList.clear();
        update();
    }
    // Delete 删除
    else if (event->key() == Qt::Key_Delete) {
        qDebug() << "Delete键被按下";
        if (seclectedShape != nullptr) {
            qDebug() << "删除选中图形";
            // 使用已有的删除功能
            onDeleteshapeTriggered();
            saveToUndoStack();
        } else if (seclectedShapeList.size() > 0) {
            qDebug() << "删除多个选中图形";
            // 使用已有的删除功能
            onDeleteshapeTriggered();
            saveToUndoStack();
        }
    }
    // Ctrl+A 全选
    else if (event->key() == Qt::Key_A && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "全选图形";
        seclectedShapeList.clear();
        seclectedShapeList = shapeList;
        update();
    }
    // Ctrl+Z 撤销
    else if (event->key() == Qt::Key_Z && event->modifiers() == Qt::ControlModifier) {
        qDebug() << "撤销操作";
        undo();
    }
    
    // 确保事件被处理
    event->accept();
    
    // 调用父类的事件处理函数
    QWidget::keyPressEvent(event);
}

void CanCvns::saveToUndoStack()
{
    // 如果连续短时间内多次调用，可能会造成性能问题和内存占用
    // 使用静态变量和简单的节流机制避免频繁保存状态
    static QTime lastSaveTime = QTime::currentTime();
    QTime currentTime = QTime::currentTime();
    
    // 如果距离上次保存不足50毫秒且队列不为空，则跳过（基本的节流）
    if (!undoStack.isEmpty() && lastSaveTime.msecsTo(currentTime) < 50) {
        return;
    }
    
    lastSaveTime = currentTime;
    
    // 创建当前状态的深拷贝，使用预分配大小提高效率
    QList<MyShape*> currentState;
    currentState.reserve(shapeList.size()); // 预分配内存
    
    for (MyShape* shape : shapeList) {
        MyShape* copy = shape->clone();
        currentState.append(copy);
    }
    
    // 保存到撤销栈
    undoStack.push(currentState);
    
    // 限制撤销栈大小，防止内存占用过大
    if (undoStack.size() > MAX_UNDO_STEPS) {
        QList<MyShape*> oldState = undoStack.takeFirst();
        clearShapeList(oldState);
    }
}

void CanCvns::undo()
{
    if (undoStack.isEmpty()) {
        return;
    }
    
    // 清除当前状态
    clearShapeList(shapeList);
    
    // 恢复上一个状态
    QList<MyShape*> previousState = undoStack.pop();
    
    // 预分配空间提高效率
    shapeList.reserve(previousState.size());
    
    for (MyShape* shape : previousState) {
        MyShape* copy = shape->clone();
        shapeList.append(copy);
    }
    
    // 清理临时状态
    clearShapeList(previousState);
    
    seclectedShape = nullptr;
    seclectedShapeList.clear();
    update();
}

// 添加全选方法实现
void CanCvns::selectAll()
{
    if (shapeList.size() > 0) {
        seclectedShapeList.clear();
        seclectedShapeList = shapeList;
        update();
        qDebug() << "全选了" << shapeList.size() << "个图形";
    }
}

// 实现清理图形列表的辅助方法
void CanCvns::clearShapeList(QList<MyShape*> &list)
{
    qDeleteAll(list); // Qt提供的更高效的批量删除方法
    list.clear();
}
